--
-- Author: yawei.zhu
-- Date: 2018-09-20 16:44:19
--
-- TaskTrackActivityRender
--

local ClassRef = app.mvc.createListViewCell(...)
local CrossServerGuildWarHelper = require("app.crossServer.views.guildWar.CrossServerGuildWarHelper")
--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.TrackTaskActivityItem))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    self:setContentSize(self._ui.Panel:getContentSize())

    self._ui.button:addClickEventListener(function()
        if not self._data then return end
        local data = self._data
        if data.type == 1 then --冠军赛
            if DungeonManager:isInDungeon() then
                display.pushToast(L("throneDungeonNotice"))
            else
                app:getInst("PvpModel"):reqEnterThroneMap()
            end
        elseif data.type == 2 then -- 世界boss,直接打开worldboss界面
            app:sendMsg("WorldBossController", "openView", 1)
        elseif data.type == 3 then -- 挑战赛，打开挑战赛界面
            app:sendMsg("PvpChallengeController", "openView")
        elseif data.type == 4 then
            UIHandler:handleMessage({id = Constant.FUNC_TYPE_CS_GUILD_WAR,mode = "open"})
        elseif data.type == 5 then
            UD.csEliteMatch:C2S_GetCrossCombatInfo(function()
                local playId = data.data.playId
                if playId then
                    app:sendMsg("PvpEliteController", "openView", playId)
                end
            end)
        elseif data.type == 6 then
            local param = {targetId=data.data.targetId}
            UIHandler:handleMessage({id = Constant.FUNC_TYPE_TEAMMATCHING, mode = "open", data=param})
        end
    end)

    self:refresh()
end

function ClassRef:removeScheduler()
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end
end

function ClassRef:_tick(dt)
    if not self._endTime then return end
    local data = self._data
    local activityData = data.data
    local remainedTime = math.floor(self._endTime - app.session:getServerTime())
    if remainedTime < 0 then remainedTime = 0 end
    local str = string.format(L("worldBoss_leftTimes"), TimeUtil.secondsToTime(remainedTime))
    self._ui.Text:setString(str)

    -- 冠军赛处理, 倒计时结束，刷新一次
    if remainedTime <= 0 and data.type == 1 then
        self._ui.Text_name:setString(L("lua_code_text_450"))
        self._ui.Text:setString(L("lua_code_text_338"))
        self:removeScheduler()
    end
    -- 挑战赛/跨服精英赛一样的处理
    if (data.type == 3 or data.type == 5) and activityData.state == "matching" then
        local waitTime = math.floor(app.session:getServerTime() - activityData.startMatchStamp)
        if waitTime >= 3600 * 5 then
            -- 等待时间超过5小时，说明数据不对
            self._ui.Text:setString(L("tips_3000105"))
        else
            self._ui.Text:setString(string.format(L("challengeTips11"), TimeUtil.secondsToTime(waitTime)))
        end
    end

    -- 跨服公会战
    if data.type == 4 then
        if remainedTime <= 0  then
            self._ui.Text:setString(L("lua_code_text_232"))
        else
            if remainedTime < 60 then
                self._ui.Text:setString(string.format(L("CSGuildWarBattleCountDown"), remainedTime))
            else
                self._ui.Text:setString(string.format(L("CSGuildWarBattleCountDown_1"), math.floor( remainedTime/60 ), remainedTime%60))
            end
        end
    end
end

function ClassRef:_tick2()
    if not self._starTime then return end

    local serverTime = math.floor(app:getServerTime())
    local costTime = serverTime - self._starTime
    local str = string.format(L("CrossServerTips1"), TimeUtil.secondsToTime(costTime))
    self._ui.Text:setString(str)
end

function ClassRef:refresh()
    if not self._data then return end
    
    local data = self._data
    local activityData = data.data
    self:removeScheduler()
    self._ui.Text_type:setString("")
    self._ui.Text_name:setPositionX(self._ui.Text_type:getPositionX())

    self._ui.bg_fail:setVisible(false)
    self._ui.bg_finish:setVisible(false)

   
    if data.type == 1 then -- 冠军赛
        self._ui.bg_finish:setVisible(true)
        
        local championData = activityData
        if championData.status == Enums.ChampionStatus.PREPARE then
        -- if app.session:getServerTime() < championData.prepareTime then
            self._ui.Text_name:setString(L("lua_code_text_373"))
            self._endTime = championData.prepareTime
            self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
            self:_tick()
        else
            self._ui.Text_name:setString(L("lua_code_text_450"))
            self._ui.Text:setString(L("lua_code_text_338"))
        end
        self._ui.icon:loadTexture(Res.TaskTrackDefaultIcon, 1)
    elseif data.type == 2 then -- 世界boss
        self._ui.bg_finish:setVisible(true)
        local worldBossInfo = activityData
        if worldBossInfo.open then
            self._ui.Text_name:setString(L("worldBossOnGoing"))
            self._endTime = activityData.endTime
            self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
            self:_tick()
        elseif worldBossInfo.rewardNotGet then
            self._ui.Text_name:setString(L("worldBossIsEnded"))
            self._ui.Text:setString(L("worldBossGetReward"))
        end
        self._ui.icon:loadTexture(Res.TaskTrackDefaultIcon, 1)
    elseif data.type == 3 then -- 挑战赛
        self._ui.bg:loadTexture("ui_resources/main/main_bg_invade_10.png", 1)
        self._ui.bg_finish:loadTexture("ui_resources/main/main_bg_invade_11.png", 1)

        self._ui.Text_type:setString(L("rank_subkey_110")) -- -- 挑战赛
        self._ui.Text_name:setPositionX(self._ui.Text_type:getPositionX() + self._ui.Text_type:getContentSize().width)
        self._ui.bg_finish:setVisible(true)
        local challengeData = activityData
        local targetConf = GD:queryTeamTargetById(challengeData.playId)
        local iconPath = string.format(Res.TeamTargetPath, targetConf.iconPath)
        self._ui.icon:loadTexture(iconPath)

        self._ui.Text_name:setString(string.format("%s", L(targetConf.name)))
        self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
        self._endTime = challengeData.endTime
        self:_tick()
    elseif data.type == 4 then -- 跨服公会战
        self._ui.Text_name:setString(L("CrossServerGuildWarTab"))
        self._ui.icon:loadTexture("ui_resources/main/war_cross_main.png", 1)
        
        self._endTime = CrossServerGuildWarHelper.getGuildWarStartTimeStampAddFirstPrepare()
        self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
        self:_tick()
    elseif data.type == 5 then -- 精英赛
        self._ui.bg:loadTexture("ui_resources/main/main_bg_invade_4.png", 1)
        self._ui.bg_finish:loadTexture("ui_resources/main/main_bg_invade_5.png", 1)

        local eliteMatchData = activityData
        if not eliteMatchData then
            self._ui.Text_name:setString("ui_csd_1063")
            return
        end
        self._ui.Text_type:setString(L("ui_csd_1063"))
        self._ui.Text_name:setPositionX(self._ui.Text_type:getPositionX() + self._ui.Text_type:getContentSize().width)
        local targetConf = GD:queryTeamTargetById(eliteMatchData.playId)
        local iconPath = string.format(Res.TeamTargetPath, targetConf.iconPath)
        self._ui.icon:loadTexture(iconPath)

        self._ui.Text_name:setString(L(targetConf.name))
        self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
        self._endTime = eliteMatchData.endTime
        self:_tick()
    elseif data.type == 6 then -- 跨服副本匹配
        self._ui.bg:loadTexture("ui_resources/main/main_bg_invade_8.png", 1)
        self._ui.bg_finish:loadTexture("ui_resources/main/main_bg_invade_9.png", 1)

        self._ui.Text_type:setString(L("ui_csd_516"))
        self._ui.Text_name:setPositionX(self._ui.Text_type:getPositionX() + self._ui.Text_type:getContentSize().width)

        local matchData = activityData
        if not matchData then
            self._ui.Text_name:setString(L("ui_csd_516"))
            return
        end

        local teamTarget = matchData.teamTarget
        self._ui.icon:loadTexture(teamTarget:getIcon())
        self._ui.Text_name:setString(teamTarget:getTaskTrackName())

        self._cronsIdx = scheduler.newCron(handler(self, self._tick2), 1, true)
        self._starTime = matchData.startTime
        self:_tick2()
    else
        self._ui.Text_name:setString("")
    end

end

function ClassRef:setTracking(flag)
    self._ui.bg_finish:setVisible(flag)
end

function ClassRef:onBtnClick(cb)
    self._onClick = cb
end


function ClassRef:onRecycleCell()
    self:removeScheduler()
end

return ClassRef
